#include "jbfile.h"


JBFile::JBFile(const std::string & filename)
{
	m_filename=filename;
	m_filename+=".class";
	unsigned char c[8]={0xCA,0xFE,0xBA,0xBE,0x00,0x00,0x00,0x32};
	for (int i=0;i<8;i++)
		write(c[i]);

}
JBFile::~JBFile()
{

}


void JBFile::save()
{
	FILE * f=fopen(m_filename.c_str(),"wb");
	if (!f)
	{
		printf("Cannot open file %s for write!\n",m_filename.c_str());
		return;
	}
	for (unsigned int i=0;i<m_bytes.size();i++)
	{
		fputc(m_bytes[i],f);
	}
	fclose(f);
}

void JBFile::print()
{
	printf("%s: \n\n",m_filename.c_str());
	for (unsigned int i=0;i<m_bytes.size();i++)
	{
		putc(m_bytes[i],stdout);
	}
	printf("\n\n");
}

void reversebytes(char * dest, char * src, unsigned int size)
{
	for (unsigned int i=0;i<size;i++)
		dest[size-i-1]=src[i];
}


unsigned short reverse(unsigned short c)
{
	unsigned short result;
	reversebytes((char*)&result,(char*)&c,sizeof(unsigned short));
	return result;
}

short reverse(short c)
{
	unsigned short result;
	reversebytes((char*)&result,(char*)&c,sizeof(short));
	return result;
}
int   reverse(int c)
{
	int result;
	reversebytes((char*)&result,(char*)&c,sizeof(unsigned int));
	return result;
}

float reverse(float c)
{
	float result;
	reversebytes((char*)&result,(char*)&c,sizeof(float));
	return result;
}

void JBFile::write(unsigned short size)
{
	unsigned short c=reverse(size);
	unsigned  char * dest=(unsigned  char*)&c;
	for (int i=0;i<sizeof(unsigned short);i++)
		write(dest[i]);
}

void JBFile::write(short size)
{
	short c=reverse(size);
	unsigned  char * dest=(unsigned  char*)&c;
	for (int i=0;i<sizeof(short);i++)
		write(dest[i]);
}

void JBFile::write(int size)
{
	int c=reverse(size);
	unsigned  char * dest=(unsigned  char*)&c;
	for (int i=0;i<sizeof(int);i++)
		write(dest[i]);
}

void JBFile::write(float size)
{
	float c=reverse(size);
	unsigned  char * dest=(unsigned  char*)&c;
	for (int i=0;i<sizeof(float);i++)
		write(dest[i]);
}

void JBFile::reserveBytes(unsigned int size)
{
	for (unsigned int i=0;i<size;i++)
		write((unsigned char)0);
}

void JBFile::writeAt(int what,int offset)
{
	int c=reverse(what);
	unsigned  char * dest=(unsigned  char*)&c;
	for (int i=0;i<sizeof(int);i++)
		m_bytes[offset+i]=dest[i];
}

void JBFile::writeAt(short what,int offset)
{
	short c=reverse(what);
	unsigned  char * dest=(unsigned  char*)&c;
	for (int i=0;i<sizeof(short);i++)
		m_bytes[offset+i]=dest[i];
}